package com.npf.imgserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.npf.imgserver.common.base.ResultBase;
import com.npf.imgserver.common.constant.Constants;
import com.npf.imgserver.common.enums.ResultCodeEnum;
import com.npf.imgserver.dao.CustomerMapper;
import com.npf.imgserver.entity.Customer;
import com.npf.imgserver.service.api.CustomerService;
import com.npf.imgserver.utils.JsonUtil;
import com.npf.imgserver.utils.RedisUtil;
import com.npf.imgserver.utils.StringUtil;
import com.npf.imgserver.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author nipengfei
 * @since 2018-09-22
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBase saveCustomer(Customer customer) {
        ResultBase resultBase = new ResultBase(ResultCodeEnum.SUCCESS);
        if (!StringUtil.isEmpty(customer)) {
            customer.setAppKey(UUIDUtil.getUUID());
            customerMapper.insert(customer);
        } else {
            resultBase.setCodeEnum(ResultCodeEnum.CUSTOMER_IS_NULL);
        }
        return resultBase;
    }

    @Override
    public Customer queryCustomerByAppKey(String appKey) {
        Customer customer = null;
        //优先查询Redis缓存 没查到结果查询数据库
        Map<Object, Object> customerMap = redisUtil.hmget(Constants.REDIS_CUSTOMER_LIST);
        if (customerMap.containsKey(appKey)) {
            //redis配置hash类型使用json序列化器 详情看RedisConfig
            //写入时会把 对象.class类型写入
            customer = (Customer) customerMap.get(appKey);
        } else {
            customer = customerMapper.selectOne(new QueryWrapper<Customer>().eq("app_key", appKey));
            if (ObjectUtils.isEmpty(customer)) {
                return null;
            }
            customerMap.put(customer.getAppKey(), customer);
            //创建符合条件的map 拷贝
            Map<String, Object> map = Maps.newHashMap();
            for (Map.Entry<Object, Object> entry : customerMap.entrySet()) {
                map.put((String) entry.getKey(), entry.getValue());
            }
            redisUtil.hmset(Constants.REDIS_CUSTOMER_LIST, map);
        }
        return customer;
    }
}
